import axios from 'axios'
import { BASE_URL, RECAPTCHA_ACTION, RECAPTCHA_KEY, REQUEST_CODE } from './config'
const { ready } = window.grecaptcha

const grecaptchaReady: Promise<boolean> = new Promise(resolve => {
  ready(() =>{
    resolve(true)
  })
})

const getCaptchaToken = (action: RECAPTCHA_ACTION)=>{
  console.log(action)
  return window.grecaptcha.execute(RECAPTCHA_KEY, {action})
}

const service = axios.create({
  baseURL: BASE_URL,
  timeout: 50000,
})

service.interceptors.request.use(
  async (config) => {
    const method = config.method?.toLocaleLowerCase()
    await grecaptchaReady
    let action = RECAPTCHA_ACTION.get
    if (['post'].includes(method || '')){
      action = RECAPTCHA_ACTION.post
    }
    const token = await getCaptchaToken(action)
    config.url =  `${config.url}?token=${token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const success = response.data.success
    if (!success) {
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  (error: any) => {
    return Promise.reject(error.response.data)
  }
)

export default service
